import Vue from "vue";
import VueRouter from "vue-router";
import ParentView from "./parent.vue";
import Layout from "../views/shou/index.vue";
import store from "../vuex/vuex";
let originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

//  处理路由替换的警告提示问题
let originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function push(location) {
  return originalReplace.call(this, location).catch((err) => err);
};
Vue.use(VueRouter);

import { list } from "../http/list";

export const routes = [
  {
    path: "/",
    component: (resovle) => require(["@/views/shou/index.vue"], resovle),
    redirect: "index",
    children: [
      {
        path: "/index",
        component: {
          render: function(h) {
            return h("div", {}, "默认首页");
          },
        },
      },
    ],
  },
  {
    path: "/table",
    component: (resovle) => require(["@/views/shou/table.vue"], resovle),
  },
  {
    path: "/login",
    component: (resovle) => require(["@/views/login/index.vue"], resovle),
  },
];

const Router = new VueRouter({
  mode: "history",
  routes: routes,
});

const component = function(path) {
  // return () => import(`../views/${path}/index.vue`);
  return (resolve) => require([`../views/${path}/index.vue`], resolve);
};

const tree = function(arr1) {
  let arrOne = [];
  let one = function(arr) {
    arr.map((res, index) => {
      let obj = {
        path: res.path,
        meta: {
          id: res.id,
          title: res.title,
          icon: res.icon,
          pid: res.pid,
        },
        component: component(res.path),
      };
      arrOne.push(obj);
      if (res.menuList) {
        one(res.menuList);
      }
    });
  };
  one(arr1);
  return arrOne;
};

function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else {
        route.component = component(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}

export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve);
};

// Router.onError((error) => {
//   const pattern = /Loading chunk (\d)+ failed/g;
//   const isChunkLoadFailed = error.message.match(pattern);
//   const targetPath = Router.history.pending.fullPath;
//   if (isChunkLoadFailed) {
//     Router.replace(targetPath);
//   }
// });

Router.beforeEach(async (to, from, next) => {
  if (sessionStorage.getItem("tree")) {
    const accessedRoutes = filterAsyncRouter(
      JSON.parse(sessionStorage.getItem("tree"))
    );
    accessedRoutes.push({
      path: "/*",
      component: {
        render(h) {
          return h("div", {}, [
            h("h1", { style: { color: "red" } }, "hello 404"),
          ]);
        },
      },
    });
    let arr = accessedRoutes.concat(routes);
    // Router.addRoutes(arr);
    store.commit("setPremRoutes", arr);
    next();
  } else {
    let { data } = await list();
    const accessedRoutes = filterAsyncRouter(data.children);
    accessedRoutes.push({
      path: "/*",
      component: {
        render(h) {
          return h("div", {}, [
            h("h1", { style: { color: "red" } }, "hello 404"),
          ]);
        },
      },
    });
    Router.addRoutes(accessedRoutes);
    let arr = accessedRoutes.concat(routes);
    store.commit("setPremRoutes", arr);
    console.log(arr);
    sessionStorage.setItem("tree", JSON.stringify(data.children));
    next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
  }
});

export default Router;
